package org.myhomework.servelet;

import org.myhomework.constant.Constants;
import org.myhomework.dao.TeacherDao;
import org.myhomework.dao.UserDao;
import org.myhomework.entity.Teacher;
import org.myhomework.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class RegisterServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/register.jsp").forward(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        // 校验用户名
        User user = UserDao.getByUserName(username);
        if (null != user) {
            req.setAttribute("msg", "用户名已被占用，请更换重试");
            req.setAttribute("back", "/register");
            req.getRequestDispatcher("/ok.jsp").forward(req, resp);
            return;
        }
        String password = req.getParameter("password");
        Integer age = Integer.parseInt(req.getParameter("age"));
        String sex = req.getParameter("sex");
        String school = req.getParameter("school");
        String course = req.getParameter("course");
        String name = req.getParameter("name");

        User newUser = new User();
        newUser.setName(name);
        newUser.setType(Constants.TEACHER_TYPE);
        newUser.setUsername(username);
        newUser.setPassword(password);
        UserDao.saveUser(newUser);

        Teacher teacher = new Teacher();
        teacher.setName(name);
        teacher.setAge(age);
        teacher.setCourse(course);
        teacher.setSchool(school);
        teacher.setSex(sex);
        teacher.setUserId(newUser.getId());
        TeacherDao.saveTeacher(teacher);

        req.setAttribute("msg", "注册成功");
        req.setAttribute("back", "/");

        req.getRequestDispatcher("ok.jsp").forward(req, resp);
    }

}
